package com.pospi.xstore.http;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.App;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.OrderBeen;
import com.pospi.xstore.dto.OrderDto;
import com.pospi.xstore.dto.PayBeen;
import com.pospi.xstore.dto.ReturnDto;
import com.pospi.xstore.greendao.OrderBeenDao;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static android.content.Context.MODE_PRIVATE;

/**
 * Created by Qiyan on 2016/6/24.
 */
public class UploadData {

    /**
     * 上传订单到服务器
     */
    public static void UploadOrderToServer(Context context, OrderDto dto) {
        int saleType;
        if (dto.getOrderType() == Constant.ORDERTYPE_SALE) {
            saleType = 1;
        } else {
            saleType = 2;
        }

        //得到店铺的Id
        SharedPreferences preferences = context.getSharedPreferences("StoreMessage", Context.MODE_PRIVATE);

        String Shopid = preferences.getString("Id", "");//得到店铺的ID

        //得到就餐的人数
        double paxNumber = 0;
        preferences = context.getSharedPreferences("Token", Context.MODE_PRIVATE);
        String value = preferences.getString("value", "");
        String[] names = value.split("\\,");
        String deviceNo = names[2];//收银机号
        String uid = names[1];

        String cashierNumber = App.getCashierMsgDto().getNumber();

        RequestParams Order = new RequestParams();
        RequestParams Order_Menus = new RequestParams();
        RequestParams Order_PayType = new RequestParams();

        List<GoodsDto> goodsDtos = SaveOrderInfo.changeToList(dto.getOrder_info());

        try {
            String random = GetData.getStringRandom(32);//得到一个32位的随机数
            Order_Menus.put("obj1", "ad18163b22b14245bf131f6d04051643");
            Order_Menus.put("createTime", GetData.getDataTime()); //当前的时间
            Order_Menus.put("discountType", 0);//就餐的人数
            Order_Menus.put("order_sid", random);
            Order_Menus.put("parentSid", "");
            Order_Menus.put("type", 1);//结束的时间
            Order_Menus.put("saleMethod", 0);//店铺的id
            Order_Menus.put("totalDiscount", "0.00");//订单的类型 1是销售，2是退货
            Order_Menus.put("number", 1);//销售方式
            Order_Menus.put("m_price", "20.00");//商品的数量
            Order_Menus.put("sid", "49611655ECB5498E9CA6A2D0E86A1AA0");//收银员号
            Order_Menus.put("price", "20.00");//收银机号
            Order_Menus.put("Uid", "f17851cbccb84ce0b55ac6f464d9e13f");//订单的唯一ID，一个32位的随机数
            Order_Menus.put("menus_sid", "2050f6519c7e427cac33ad3080af035e");//得到手机的MAC地址
            Order_Menus.put("callCount", 0);//订单号
            Order_Menus.put("menus_name", "花王护手霜");//找零的金额
            Order_Menus.put("saleprice", "20.00");//实收金额
            Order_Menus.put("obj3", 0);//盈利的金额
            Order_Menus.put("lineNum", 1);//订单的状态，4是正常销售，上传的时候用
            Order_Menus.put("status", 4);//盈利的金额
            Order_Menus.put("singleDiscount", "0.00");//订单的状态，4是正常销售，上传的时候用

            Order.put("obj1", "");
            Order.put("paxNumber", 0);
            Order.put("obj6", "");//订单的唯一数据
            Order.put("remoney", "20.00");
            Order.put("cashNo", "100123");//订单的类型,销售或者退货
            Order.put("obj10", "");
            Order.put("number", 1);
            Order.put("type", 1);
            Order.put("obj4", "");
            Order.put("acmoney", "20.00");
            Order.put("obj9", "");
            Order.put("date", GetData.getDataTime());
            Order.put("imel", "POSPi-uuid-3E57B975-9855-49AB-804F-9AF0D9015558");
            Order.put("saleMethod", 0);
            Order.put("obj2", "");
            Order.put("obj7", "");
            Order.put("sid", random);
            Order.put("no", "1606270003");
            Order.put("uid", "f17851cbccb84ce0b55ac6f464d9e13f");
            Order.put("discount", "0.00");
            Order.put("obj5", "");
            Order.put("cgmoney", "0.00");
            Order.put("by", "0000");
            Order.put("shopNo", "ad18163b22b14245bf131f6d04051643");
            Order.put("obj3", "");
            Order.put("status", 4);
            Order.put("obj8", "");


            Order_PayType.put("obj3", "");
            Order_PayType.put("price_ys", "20.00");
            Order_PayType.put("orderBy", 0);
            Order_PayType.put("lineNum", 1);
            Order_PayType.put("payId", "A33C386612F140CC9D5177535AF3ACF2");
            Order_PayType.put("obj2", "0");
            Order_PayType.put("payType", 1);
            Order_PayType.put("obj5", "");
            Order_PayType.put("price", "20.00");
            Order_PayType.put("sid", "E9C1FC0E8FF3401C8408017F25FD66DB");
            Order_PayType.put("order_sid", random);
            Order_PayType.put("name", "现金");
            Order_PayType.put("Uid", "f17851cbccb84ce0b55ac6f464d9e13f");
            Order_PayType.put("obj4", "");
            Order_PayType.put("price_zl", "0.00");
            Order_PayType.put("status", 1);


        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();//实例化后存入键值对
//        params.put("ShopId", Shopid);
        params.put("Order", Order.toString());
        params.put("Order_Menus", Order_Menus.toString());
        params.put("Order_PayType", Order_PayType.toString());
        Log.i("order", Order.toString());

        LoadServer.getConnect(context, Api.SYNCORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("上传订单成功", new String(bytes));
                if (i == 200) {
                    Log.i("向服务器发送数据成功", new String(bytes));
                    Log.i("向服务器上传订单", "上传订单");

                    try {
                        JSONObject object = new JSONObject(new String(bytes));
                        ReturnDto returnDto = new ReturnDto();
                        returnDto.setResult(object.getInt("Result"));
                        returnDto.setMessage(object.getString("Message"));
                        returnDto.setValue(String.valueOf(object.getString("Value")));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.i("上传订单失败", new String(bytes));
            }
        });

    }


    public static void upOrder(Context context, final OrderBeen dto, String payType) {
        String saleType;
        if (dto.getOrderType() == Constant.ORDERTYPE_SALE) {
            saleType = "505";
        } else {
            saleType = "506";
        }
        //得到店铺的Id
//        SharedPreferences preferences = context.getSharedPreferences("StoreMessage", MODE_PRIVATE);
        String shopid = SPHelper.getInstance().getString(Constant.STORE_ID);//得到店铺的ID
        JSONObject order = new JSONObject();
        JSONObject head = new JSONObject();
        JSONArray array = new JSONArray();
        JSONArray pay = new JSONArray();
        JSONArray headArray = new JSONArray();
        double hyzk = 0;
        double lszk = 0;
        double cxzk = 0;
        double lsj = 0;

        try {
            List<GoodsDto> goodsDtos = SaveOrderInfo.changeToList(dto.getOrder_info());
            double discount = 0;
            //订单详情
            for (int i = 0; i < goodsDtos.size(); i++) {
                GoodsDto goodsDto = goodsDtos.get(i);

                lsj += goodsDto.getOldPrice() * goodsDto.getNum();
                discount += goodsDto.getDiscount();
                hyzk += goodsDto.getHyzk();
                lszk += goodsDto.getLszk();
                cxzk += goodsDto.getCxzk();
                double sj = 0;
                double xsj = 0;
                if (goodsDto.getNum() < 0) {
                    sj = DoubleSave.doubleSaveTwo((goodsDto.getPrice() * goodsDto.getNum() + goodsDto.getDiscount())) / goodsDto.getNum();
                    xsj = DoubleSave.doubleSaveTwo(goodsDto.getPrice() * goodsDto.getNum() + goodsDto.getDiscount());
                } else if (goodsDto.getNum() == 0) {
                    sj = 0;
                    xsj = 0;
                } else {
                    sj = DoubleSave.doubleSaveTwo((goodsDto.getPrice()*goodsDto.getNum()-goodsDto.getDiscount()))/goodsDto.getNum();
                    xsj = DoubleSave.doubleSaveTwo(goodsDto.getPrice()*goodsDto.getNum()-goodsDto.getDiscount());
                }


                JSONObject json = new JSONObject();
                json.put("goodsid", goodsDto.getSid());//商品id
                json.put("sl", goodsDto.getNum());//销售数量
                json.put("lsj", goodsDto.getOldPrice());//零售价
                json.put("xsj", sj);//销售价
                json.put("zzk", goodsDto.getDiscount());//总折扣
                json.put("hyzk", goodsDto.getHyzk());//会员折扣
                json.put("popzk", goodsDto.getCxzk());//促销折扣
                json.put("lszk", goodsDto.getLszk());//临时折扣
                json.put("syje", "");//损益金额

                json.put("popid", "");//促销单id
                json.put("popbillno", "");//

                json.put("xsjje", xsj);
                json.put("lsjje", DoubleSave.doubleSaveTwo(goodsDto.getOldPrice() * goodsDto.getNum()));
                array.put(json);
            }
            String no = String.valueOf(dto.getMaxNo());
            head.put("djlb", saleType);//订单类型(505|前台销售,506|前台退货/507换货
            head.put("billno", dto.getMaxNo());//小票号
            head.put("fphm", no.substring(no.length() - 4, no.length()));//流水号
            head.put("market", SPHelper.getInstance().getString(Constant.STORE_ID));//店铺号

            head.put("syjh", "");//收银机号
            head.put("syyid", SPHelper.getInstance().getString(Constant.CUSTOMER));//收银员
            head.put("syyname", SPHelper.getInstance().getString(Constant.CUSTOMER_name));//营业员
            head.put("yyyid", SPHelper.getInstance().getString(Constant.CUSTOMER));//收银员
            head.put("yyyname", SPHelper.getInstance().getString(Constant.CUSTOMER_name));//营业员
            head.put("lsjje", DoubleSave.doubleSaveTwo(lsj));//零售价金额
            head.put("xsjje", dto.getYs_money());//销售价金额

            head.put("sfje", dto.getSs_money());//实付金额
            head.put("zl", dto.getZl_money());//找零
            head.put("zzk", discount);//总折扣
            head.put("vipqkje","");//会员欠款
            head.put("hyzk",hyzk);//会员
            head.put("popzk", cxzk);//促销折扣
            head.put("lszk", lszk);//临时折扣
            head.put("syje", 0);//损益金额
            head.put("vipjf", "");//积分
            head.put("memo", "");//
            head.put("vipid", dto.getVipNumber());
            head.put("vipje", "");//零钱余额
            head.put("grantid", "");
            head.put("sendrq", dto.getCheckoutTime());


            //    "paytype": "微信",              //支付方式
            //        "payje": "2",                      //支付金额
            //        "paynum": "",                    //卡号
            //        "ye": "0",                          //消费前余额
            //        "memo": ""                       //备注

            List<PayBeen> payBeens = SaveOrderInfo.changepay(dto.getPayway());

            for (PayBeen ob:payBeens) {
                JSONObject object = new JSONObject();
                object.put("payid", ob.getId());
                object.put("paytype", "");
                object.put("payje", ob.getSs());
                object.put("paynum", "");
                object.put("ye", "");
                object.put("memo", "");
                pay.put(object);
            }



            headArray.put(head);
            order.put("head", headArray);
            order.put("pay", pay);
            order.put("detail", array);

        } catch (Exception e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.put("model", "bill.mpossell");
        params.put("fun", "save");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("pds", order.toString());

        Log.i("上传订单", "params" + params.toString());
        LoadServer.getConnect(context, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("errCode").equals("100")) {
                        OrderBeenDao dao = App.getInstance().getDaoSession().getOrderBeenDao();
                        OrderBeen orderBeen = dao.queryBuilder().where(OrderBeenDao.Properties.MaxNo.eq(dto.getMaxNo())).unique();
                        orderBeen.setUpStatus(Constant.UP_OK);
                        dao.update(orderBeen);
                    }
                    Log.i("up", object.getString("errMsg"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.i("上传订单失败", new String(bytes));
            }
        });

//        new Server().getConnect(context, new URL().SYNCORDER, params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int i, Header[] headers, byte[] bytes) {
//                if (i == 200) {
//                    LoginReturnDto returnDto = new LoginReturnDto();
//                    try {
//                        Log.i("up", new String(bytes));
//                        JSONObject object = new JSONObject(new String(bytes));
////                        Log.i("up", object.toString());
//                        returnDto.setResult(Integer.parseInt(object.getString("code")));
//                        if (returnDto.getResult() == 200) {
//                            Log.i("上传订单", "向服务器发送数据成功" + new String(bytes));
//                            JSONObject data = object.getJSONObject("data");
//                            String billid = data.getString("billid");
//                            String billtype = data.getString("billtype");
////                            kucunUp(billid,billtype);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                } else {
//                    Log.i("上传订单", "上传订单失败：" + new String(bytes));
//                }
//            }
//
//            @Override
//            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                try {
//                    Log.i("上传订单", "上传订单失败：" + new String(bytes));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
    }


}
